package com.xhtt.modules.app.controller.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.exception.RRExceptionEnum;
import com.xhtt.common.utils.*;
import com.xhtt.common.validator.ValidatorUtils;
import com.xhtt.modules.app.annotation.Login;
import com.xhtt.modules.app.annotation.LoginUser;
import com.xhtt.modules.cfg.entity.CfgStand;
import com.xhtt.modules.cfg.service.CfgStandService;
import com.xhtt.modules.sys.controller.AbstractController;
import com.xhtt.modules.sys.entity.SysDeptEntity;
import com.xhtt.modules.sys.entity.SysUserEntity;
import com.xhtt.modules.sys.service.SysUserService;
import com.xhtt.modules.task.entity.*;
import com.xhtt.modules.task.model.car.ArrangeUserModel;
import com.xhtt.modules.task.model.car.AssignTaskModel;
import com.xhtt.modules.task.service.TaskCarPlanService;
import com.xhtt.modules.task.service.TaskCarSeoLogService;
import com.xhtt.modules.task.service.TaskCarTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 排车任务
 * </p>
 *
 * @author feipc
 * @since 2019-02-26
 */
@Api(tags = "任务平台-排车任务", value = "任务平台-排车任务")
@RestController
@RequestMapping("app/task/rowcar")
public class TaskRowCarController extends AbstractController {

    @Autowired
    private TaskCarPlanService taskCarPlanService;
    @Autowired
    private TaskCarTaskService taskCarTaskService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CfgStandService cfgStandService;
    @Autowired
    private TaskCarSeoLogService taskCarSeoLogService;

    /**
     * 计划管理列表
     */
    @GetMapping(value = "/planList")
    @ApiOperation("计划管理列表(web)")
    @Login
    public R planList(@RequestParam Map<String, Object> params) {
        PageUtils page = taskCarPlanService.planList(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 获取排车计划详情
     */
    @GetMapping(value = "/getPlan/{id}")
    @ApiOperation("获取排车计划详情（web）")
    @Login
    public R getPlan(@PathVariable("id") Integer id) {
        TaskCarPlan plan = taskCarPlanService.getById(id);
        if (null != plan && null != plan.getStageId()) {
            CfgStand stand = cfgStandService.getById(plan.getStageId());
            plan.setStageName(null == stand ? "" : stand.getName());
        }
        return R.ok().put(Constant.DATA, plan);
    }

    /**
     * 新增排车计划
     */
    @PostMapping(value = "/addPlan")
    @ApiOperation("新增排车计划（web）")
    @Login
    public R addPlan(@RequestBody TaskCarPlan taskCarPlan) {
        taskCarPlanService.addPlan(taskCarPlan);
        return R.ok();
    }

    /**
     * 新增排车计划(外部调用)
     */
    @PostMapping(value = "/request_car_info")
    @ApiOperation("新增排车计划(外部调用)")
    public R addPlanFromOut(@RequestBody TaskCarPlan taskCarPlan) {
        String serialNo = taskCarPlanService.addPlanFromOut(taskCarPlan);
        return R.ok().put("serialNo", serialNo);
    }

    /**
     * 修改排车计划
     */
    @PostMapping(value = "/updatePlan")
    @ApiOperation("修改排车计划（web）")
    @Login
    public R updatePlan(@RequestBody TaskCarPlan taskCarPlan) {
        taskCarPlanService.updatePlan(taskCarPlan);
        return R.ok();
    }

    /**
     * 删除排车计划
     */
    @PostMapping(value = "/deletePlan")
    @ApiOperation("删除排车计划（web）")
    @Login
    public R deletePlan(@RequestBody Integer[] ids) {
        taskCarPlanService.removeByIds(Arrays.asList(ids));
        taskCarTaskService.remove(new LambdaQueryWrapper<TaskCarTask>().in(TaskCarTask::getCarPlanId, Arrays.asList(ids)));
        return R.ok();
    }

    /**
     * 任务分配列表
     */
    @GetMapping(value = "/taskList")
    @ApiOperation("任务分配列表（排车任务-任务管理-装车台状态）(web/app)")
    @Login
    public R taskList(@RequestParam Map<String, Object> params) {
        PageUtils page = taskCarTaskService.taskList(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 获取排车任务部门-组-用户数据
     *
     * @param disableNotTeam 传入true代表只能选择组以下的用户
     */
    @ApiOperation("获取排车任务部门-组-用户数据(web)")
    @GetMapping("/deptTeamUser")
    @Login
    public R deptTeamUser(@RequestParam(value = "disableNotTeam", required = false, defaultValue = "false") boolean disableNotTeam) {
        List<SysDeptEntity> list;
        if (disableNotTeam) {
            list = sysUserService.teamUser();
        } else {
            list = sysUserService.deptTeamUser();
        }
        return R.ok().put(Constant.DATA, list);
    }

    /**
     * 分配任务（把人安排到岛上）
     */
    @PostMapping(value = "/assignTask")
    @ApiOperation("分配任务（web/app）")
    @Login
    public R assignTask(@RequestBody AssignTaskModel model) {
        ValidatorUtils.validateEntity(model);
        taskCarTaskService.assignTask(model);
        return R.ok();
    }

    /**
     * 任务列表
     */
    @GetMapping(value = "/taskWorkingList")
    @ApiOperation("排车任务-任务管理-任务列表(app)")
    @Login
    public R taskWorkingList(@RequestParam Map<String, Object> params) {
        PageUtils page = taskCarTaskService.taskWorkingList(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 排车任务-现场操作列表
     */
    @GetMapping(value = "/operList")
    @ApiOperation("排车任务-现场操作列表(app)")
    @Login
    public R operList(@RequestParam Map<String, Object> params, @ApiIgnore @LoginUser SysUserEntity user) {
        params.put("userId", user.getUserId());
        PageUtils page = taskCarTaskService.taskWorkingList(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 排车任务-现场操作-开始操作
     */
    @PostMapping(value = "/start")
    @ApiOperation("排车任务-现场操作-开始操作(app)")
    @Login
    public R start(Integer planId) {
        TaskCarTask t = new TaskCarTask();
        t.setStartDate(LocalDateTime.now());
        taskCarTaskService.update(t, new LambdaQueryWrapper<TaskCarTask>().eq(TaskCarTask::getCarPlanId, planId));
        return R.ok();
    }

    /**
     * 排车任务-现场操作-查看任务详情
     */
    @GetMapping(value = "/operDetail")
    @ApiOperation("排车任务-现场操作-查看任务详情(app)")
    @Login
    public R operDetail(@RequestParam Integer planId) {
        TaskCarTask db = taskCarTaskService.getOne(new LambdaQueryWrapper<TaskCarTask>().eq(TaskCarTask::getCarPlanId, planId));
        return R.ok().put(Constant.DATA, db);
    }

    /**
     * 排车任务-现场操作-临时保存
     */
    @PostMapping(value = "/operTempSave")
    @ApiOperation("排车任务-现场操作-临时保存(app)")
    @Login
    public R operTempSave(@RequestBody TaskCarTask taskCarTask) {
        Integer planId = taskCarTask.getCarPlanId();
        if (null == planId) {
            throw new RRException("参数有误");
        }
        TaskCarTask db = taskCarTaskService.getOne(new LambdaQueryWrapper<TaskCarTask>().eq(TaskCarTask::getCarPlanId, planId));
        if (null == db) {
            throw new RRException("对象不存在");
        }
        CopyUtils.copyProperties(taskCarTask, db);
        if (CollectionUtils.isNotEmpty(taskCarTask.getFiles())) {
            db.setPhoto(JSON.toJSONString(taskCarTask.getFiles()));
        }
        taskCarTaskService.updateById(db);
        return R.ok();
    }

    /**
     * 排车任务-现场操作-完成任务
     */
    @PostMapping(value = "/operComplete")
    @ApiOperation("排车任务-现场操作-完成任务(app)")
    @Login
    public R operComplete(@RequestBody TaskCarTask taskCarTask, @ApiIgnore @LoginUser SysUserEntity user) {
        Integer planId = taskCarTask.getCarPlanId();
        if (null == planId) {
            throw new RRException("参数有误");
        }

        taskCarTaskService.operComplete(taskCarTask, user.getUserId().intValue());
        return R.ok();
    }

    /**
     * 交接班
     */
    @ApiOperation("交接班(app)")
    @PostMapping("/changeShifts")
    @Login
    public R changeShifts(@RequestBody TaskCarTaskUser carTaskUser, @ApiIgnore @LoginUser SysUserEntity user) {
        // 把自己没完成的排车任务分给别人啦
//        Integer selfId = user.getUserId().intValue();
        taskCarTaskService.changeShifts(user, carTaskUser);

        return R.ok();
    }

    /**
     * 交接班-组长安排接班人
     */
    @ApiOperation("交接班-组长安排接班人(app)")
    @PostMapping("/arrangeUser")
    @Login
    public R arrangeUser(@RequestBody ArrangeUserModel model, @ApiIgnore @LoginUser SysUserEntity user) {
        taskCarTaskService.arrangeUser(model, user);

        return R.ok();
    }

    /**
     * 综合查询-核心任务表
     */
    @GetMapping(value = "/core/list")
    @ApiOperation("综合查询-核心任务表(web)")
    @Login
    public R coreList(@RequestParam Map<String, Object> params) {
        PageUtils page = taskCarPlanService.coreList(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 综合查询-核心任务表-排车任务导出
     */
    @GetMapping(value = "/core/export")
    @ApiOperation("综合查询-核心任务表-排车任务导出")
    @Login
    public void coreExport(HttpServletResponse response, @RequestParam Map<String, Object> params) {

        ExportExcel exportExcel = new ExportExcel();
        params.put("limit", "650000");
        PageUtils page = taskCarPlanService.coreList(params);
        List list = page.getList();
        String fileName = "排车任务";
        String sheetName = "sheet1";
        String[] headers = {"车号", "台号", "产品", "数量", "班组人员", "过磅时间", "状态"};
        String[] columns = {"carNo", "stageName", "productName", "number", "userName", "dateWeigh", "status"};
        try {
            exportExcel.exportExcel(fileName, sheetName, headers, columns, list, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(RRExceptionEnum.EXPORT_FAIL);
        }
    }

    /**
     * 槽车一览表
     */
    @GetMapping(value = "/core/seo")
    @ApiOperation("槽车一览表(web)")
    @Login
    public R seoList(@RequestParam Map<String, Object> params) {
        PageUtils page = taskCarPlanService.seoList(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 编辑槽车一览表
     */
    @PostMapping(value = "/core/seoEdit")
    @ApiOperation("编辑槽车一览表(web)")
    @Login
    public R seoEdit(@RequestBody TaskCarSeo seo, @ApiIgnore @LoginUser SysUserEntity user) {
        taskCarPlanService.seoEdit(seo, user);
        return R.ok();
    }

    /**
     * 槽车一览表日志
     */
    @GetMapping(value = "/core/seoLog")
    @ApiOperation("编辑槽车一览表日志(web)")
    @Login
    public R seoLog(@RequestParam Integer id) {
        List<TaskCarSeoLog> list = taskCarSeoLogService.list(new LambdaQueryWrapper<TaskCarSeoLog>().eq(TaskCarSeoLog::getId,id));
        return R.ok().put(Constant.DATA, list);
    }

    /**
     * 槽车一览表-导出
     */
    @GetMapping(value = "/core/seoExport")
    @ApiOperation("槽车一览表(web)")
    @Login
    public R seoListExport(@RequestParam Map<String, Object> params, HttpServletResponse response) {
        params.put("limit", "65000");
        ExportExcel exportExcel = new ExportExcel();
        PageUtils page = taskCarPlanService.seoList(params);
        List list = page.getList();

        String fileName = "槽车任务";
        String sheetName = "槽车任务";
        String[] headers = {"日期", "车号", "产品", "罐号", "台号", "装车人员", "门卫登记时间", "开票时间", "过磅时间", "到达装车台时间", "启泵时间", "停泵时间", "离开装车台时间","状态"};
        String[] columns = {"date", "carNo", "productName", "potNo", "stageName", "userName", "dateRegister", "dateInvoice", "dateWeigh", "stageUpDate", "pumpUpDate", "pumpDownDate", "stageDownDate","status"};
        try {
            exportExcel.exportExcel(fileName, sheetName, headers, columns, list, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(RRExceptionEnum.EXPORT_FAIL);
        }
        return R.ok().put(Constant.DATA, page);
    }
}
